/**
 * @description 接口-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const fs = require('fs')
const ox = require('@daelui/oxjs')
const Service = require('./service.js')
const { filer } = require('@daelui/oxkit')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 增删改事件触发
  */
  emit (name, action, res) {
    super.emit(name, action, res)
    res = res || {}
    if (res.success) {
      this.syncPluginsCode()
    }
  }

  /**
   * @function 同步插件编码
  */
  syncPluginsCode () {
    this.$service.queryAll({
      params: {
        status: '1'
      },
      excute: {
        sort: [
          {field: 'status', by: 'EQUAL'},
          {field: 'createTime', by: 'desc'},
          {field: 'order', by: 'desc'}
        ]
      }
    }).then(res => {
      let list = res.data
      list = Array.isArray(list) ? list : []
      // 只取出启用的
      list = list.filter(item => {
        return String(item.status) === '1' || String(item.status) === 'true'
      }).map(item => {
        try {
          item.matchRules = JSON.parse(item.matchRules)
        } catch (e) {
          item.matchRules = []
        }
        try {
          item.transformRules = JSON.parse(item.transformRules)
        } catch (e) {
          item.transformRules = []
        }
        // 匹配规则
        let matchRules = ''
        item.matchRules = Array.isArray(item.matchRules) ? item.matchRules : []
        item.matchRules.forEach(node => {
          let match = /func/.test(node.matchType) ? node.matchValueCompiled : /reg/.test(node.matchType) ? node.matchValue : "'" + node.matchValue + "'"
          if (node.matchItem && match && node.matchMode !== '') {
            matchRules += `{id: '${node.id}', matchItem: '${node.matchItem}', match: ${match}, matchMode: '${node.matchMode}'}, `
          }
        })
        matchRules =  matchRules.replace(/},\s+$/, '}')
        matchRules = '[' + matchRules + ']'
        // 转换规则
        let transformRules = ''
        item.transformRules = Array.isArray(item.transformRules) ? item.transformRules : []
        item.transformRules.forEach(node => {
          let transform = /func/.test(node.transformType) ? node.transformValueCompiled : /reg/.test(node.transformType) ? node.transformValue : "'" + node.transformValue + "'"
          if (node.transformItem && transform && String(node.transformMode) === '1') {
            transformRules += `{id: '${node.id}', transformItem: '${node.transformItem}', transform: ${transform}, transformMatch: '${node.transformMatch || ''}'}, `
          }
        })
        transformRules = transformRules.replace(/},\s+$/, '}')
        transformRules = '[' + transformRules + ']'
        return `proxiers.push({
  id: '${item.id}',
  name: '${item.name}',
  serviceType: '${item.serviceType}',
  matchRules: ${matchRules},
  transformRules: ${transformRules},
  isMatchParams: '${item.isMatchParams}',
  matchParams: '${item.matchParams}',
  isBeforeDebugger: '${item.isBeforeDebugger || false}',
  isAfterDebugger: '${item.isAfterDebugger || false}'
})`
      })
      let content = `(function(){
var module = window.module || {}
var exports = window.exports || {}
var proxiers = []
var $dog = window.$dog || function(){}
$dog.proxiers = proxiers
window.$dog = $dog
${list.join('\n\n')}
})();
`
      let config = this.route.scope.CONFIG
      let path = config.constant.proxierPath
      // 文件不存在
      let dir = path.replace(/\/\w+\.js/, '')
      if (!fs.existsSync(dir)) {
        filer.buildPath(dir)
      }
      // 文件写入
      try {
        fs.writeFileSync(
          path, content
        )
      } catch (e) {}
    })
  }
}

module.exports = Controller